// 获取用户session userInfo
const jwt = require("jsonwebtoken");
const { User } = require("../models");

let userSessions = {};
async function userInfo(req, showPassword = false) {
  let user = "";
  let { token, originname } = req.headers;
  originname = originname ? originname : "/";

  if (token && token != "undefined") {
    // 验证 token 是否正确
    const decoded = jwt.verify(token, process.env.SECRET);
    // 从 jwt 中，解析出之前存入的 userId
    const { userId } = decoded;
    // 查询一下，当前用户
    let condition = {};
    if (!showPassword) {
      condition = {
        attributes: { exclude: ["password"] },
      };
    }

    user = await User.findByPk(userId, condition);
  }
  return {
    user,
    originname,
  };
}

module.exports = {
  userInfo,
  userSessions,
};
